const express = require('express')

// 由于引入了babel/register，这里可以直接使用ES6语法
import React from 'react';
import ReactDOMServer from "react-dom/server";
import Document from "../components/Document";
import App from '../components/App';
import { StaticRouter, matchPath} from "react-router-dom";
import routes from '../core/routes';

const router = express.Router();

// *为了让匹配到的路由都交给路由处理函数
// 将路由处理从 router.get 转移到 StaticRouter
router.get('*', async (req, res) => {
  if(req.path === '/favicon.ico') return;   // 移除浏览器请求favicon.ico的情况

  let data = {}
  let getData = null

  routes.some(route => {
    const match = matchPath(req.path, route);         // match 路径匹配
    if(match) {
      getData = (route.component || {}).getData       // 获取对应组件挂载的getData
    }
    return match
  })

  if(typeof getData === 'function') { 
    try {
      data = await getData()
    } catch (error) {}
  }
  console.log(data)

  // 渲染动态App组件
  const appString = ReactDOMServer.renderToString(
    <StaticRouter
      location={req.url}
      context={data}
    >
      <App />
    </StaticRouter>
  )

  // 渲染静态内容Document组件
  const html = ReactDOMServer.renderToStaticMarkup(<Document data={data}>{appString}</Document>)

  res.send(html)
})

module.exports = router